package com.ashes.telbots.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author chengxuhui
 * @description 描述
 */
@Slf4j
public class WeatherUtils {
    private static final String API_URL = "http://shanhe.kim/api/za/tianqi.php";

    public static StringBuilder getWeatherInfo(String city) {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(API_URL + "?city=" + city)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                JSONObject parseObject = JSONObject.parseObject(response.body().string());
                log.info("ssss,{}", parseObject);

                JSONObject data = parseObject.getJSONObject("data");
                log.info("ssss,{}", data);
                // 获取current对象
                JSONObject current = data.getJSONObject("current");
                // 获取city字段的值
                String city1 = current.getString("city");
                String temp = current.getString("temp");
                String air = current.getString("air");
                StringBuilder builder = new StringBuilder();
                builder.append("城市：" + city1).append(",温度:" + temp).append(",空气指数:" + air);
                return builder;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
